package com.example.memo;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;

import android.widget.ListAdapter;

import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.example.memo.Bean.noteBean;
import com.example.memo.Services.FilterListener;
import com.example.memo.Services.ResultListener;
import com.example.memo.db.MysqlOpenHelper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;



public class NoteFragment extends Fragment implements View.OnClickListener{

    //添加控件
    private ImageView addNote;
    //列表网格
    private GridView M_listViewID;
    //搜索
    private MyAdapter3 myadapter2=null;
    private Spinner spinner;
    private EditText editTextsearch;
    private ListView listViewsearch;
    //定义数据
    private List<noteBean> note_data = new ArrayList<>();
    private List<String> lists=new ArrayList<>();
    //用户数据筛选
    private SQLiteDatabase sqLiteDatabase;
    private Myadapter myadapter;
    //常量
    private TextView count;

    private String[] Types;
  private Multimap<String, String> multimap ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fragment_note, container, false);
        //全部笔记的下拉框
        //初始化控件
        initView(view);
        initData();
        //获取数据库数据
        getData();
        //分类筛选
        sortSift();
        //设置listview
        if(note_data!=null){
            setListView();
        }

        //导入数据进myAdapter3
        setData();
        //输入监听
        setListeners();

        return view;
    }
public void initView(View view){
    addNote = view.findViewById(R.id.add1);
    addNote.setOnClickListener(this::onClick);
    count = view.findViewById(R.id.count);
    //列表的初始化
    M_listViewID = view.findViewById(R.id.gview);
    //分类筛选
    spinner = view.findViewById(R.id.my_spinner);
    editTextsearch = (EditText) view.findViewById(R.id.et_searchtext);
    listViewsearch = (ListView) view.findViewById(R.id.Search_data);
}

    public void initData(){
        //插入数据时注意，一定要传入最新的数据库版本号
        MysqlOpenHelper mysqlOpenHelper=new MysqlOpenHelper(getActivity());
        sqLiteDatabase=mysqlOpenHelper.getWritableDatabase();
    }

    //获取数据
    public void getData() {
        String[] ziduan = {"bt","neirong","create_time","img","id","fenglei","update_time"};
        Cursor cursor=sqLiteDatabase.query("note_table",ziduan,null,null
                ,null,null,null);
        ArrayList<noteBean> noteBeans = new ArrayList<>();
        ArrayList<String> list = new ArrayList<>();
        ArrayList<String> listType = new ArrayList<>();
        multimap = ArrayListMultimap.create();
        //判空
        if (cursor.getCount()>0){
            int value1=cursor.getColumnIndex("neirong");
            int value2=cursor.getColumnIndex("create_time");
            int value3=cursor.getColumnIndex("img");
            int value4=cursor.getColumnIndex("bt");
            int value5=cursor.getColumnIndex("id");
            int value6=cursor.getColumnIndex("fenglei");
            int value7=cursor.getColumnIndex("update_time");

            while (cursor.moveToNext()) {
                String   nr = cursor.getString(value1);
                String   time = cursor.getString(value2);
                String   img = cursor.getString(value3);
                String   bt = cursor.getString(value4);
                String   id=cursor.getString(value5);
                String   fenglei = cursor.getString(value6);
                String   utime = cursor.getString(value7);
                //把日期转为相应的格式
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日 HH:mm");
                String format = dateFormat.format(new Date(time));
                //String format2 = dateFormat.format(new Date(utime));
                noteBean noteBean = new noteBean();
                noteBean.setNeirong(nr);
                noteBean.setBt(bt);
                noteBean.setCreate_time(format);
                noteBean.setImg(img);
                noteBean.setId(id);
                noteBean.setFenglei(fenglei);

                noteBeans.add(noteBean);
                //用于搜索
                list.add(bt);
                list.add(nr);
                listType.add(fenglei);
                multimap.put("标题",bt);
                multimap.put("内容",nr);
            }
            note_data=noteBeans;
            lists=list;

            // 创建一个新的 ArrayList 来存储非空值
            ArrayList<String> filteredList = new ArrayList<>();
            for (String str:listType) {
                if(str!=null&&!str.isEmpty()){
                    // 创建一个新的 ArrayList 来存储非空值
                    filteredList.add(str);
                }

            }
            //遍历分类名称用于添加未定义分类
           String[]  distinctArray= filteredList.toArray(new String[filteredList.size()]);
            // 使用 LinkedHashSet 过滤重复元素并保留顺序
            LinkedHashSet<String> set = new LinkedHashSet<>(Arrays.asList(distinctArray));
            // 将结果转换回数组
            Types = set.toArray(new String[0]);
            // 打印去重后的数组元素
          // System.out.println(Arrays.toString(Types));

        }else {
            note_data=noteBeans;
            Toast.makeText(getActivity(), "wait获取信息失败", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    //搜索的设置数据
    private void setData() {
        // 这里创建adapter的时候，构造方法参数传了一个接口对象，这很关键，回调接口中的方法来实现对过滤后的数据的获取
        myadapter2 = new MyAdapter3(lists,multimap, getContext(), new FilterListener() {
            // 回调方法获取过滤后的数据
            public void getFilterData(List<String> list) {
                // 这里可以拿到过滤后数据，所以在这里可以对搜索后的数据进行操作
                Log.e("TAG", "接口回调成功");
                Log.e("TAG", list.toString());
                setItemClick(list);
            }
        });
        listViewsearch.setAdapter(myadapter2);

    }


  //数据导入listview视图,并实现高度自适应，和统计总数
    public void  setListView(){
        myadapter = new Myadapter(note_data, getContext(), new ResultListener() {
            @Override
            public void getNoteData(List<noteBean> lists) {
                Log.e("TAG", "删除接口回调成功");
                Log.e("TAG", lists.toString());
                //加载适配器
                M_listViewID.setAdapter(myadapter);
                //实现列表高度自适应
                setGridViewHeightBasedOnChildren(M_listViewID);
                count.setText(String.valueOf(note_data.size()) + "条笔记");
            }
        });
        //加载适配器
        M_listViewID.setAdapter(myadapter);
        //实现列表高度自适应
        setGridViewHeightBasedOnChildren(M_listViewID);
        count.setText(String.valueOf(note_data.size()) + "条笔记");
    }
    public static void setGridViewHeightBasedOnChildren(GridView gridView) {
        //获取 gridView 的适配器
        ListAdapter adapter = gridView.getAdapter();
        if (adapter == null) {
            return;
        }
        //定义总高度
        double totalHeight;
        //获取item数量
        int itemsCount = adapter.getCount();
        //获取列数
        //int columnsCount = gridView.getNumColumns();
        int columnsCount = 2;
        //获取行数量
        int rowsCount = (int) Math.ceil((double) itemsCount / (double) columnsCount);
        //获取 GridView 的第一个子项。
        View item = adapter.getView(0, null, gridView);
        //测量子项的高度和宽度。
        item.measure(0, 0);
        //计算总高度
        totalHeight =1.3* item.getMeasuredHeight();

        // 加上所有行之间的垂直间距
        totalHeight += (rowsCount - 1) * gridView.getVerticalSpacing();

        // 获取 gridView 的父布局
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = (int) totalHeight;
        gridView.setLayoutParams(params);
        // 设置滚动到最底部
        gridView.smoothScrollToPosition(adapter.getCount());
    }


    //搜索时查找对应的id
    public String  getIdByStr1(List<noteBean> note_data, String str1) {
       // 找不到id时为-1
        String id = null;
        if (note_data ==null){
            return null;
        }
        for (int i = 0; i < note_data.size(); i++) {
            noteBean item = note_data.get(i);
            if (str1.equals(item.getBt())||str1.equals(item.getNeirong())){
                id = item.getId();
                break;
            }
        }
        return id;
    }
    //分类筛选
    public  void  sortSift(){
        String[] items=getResources().getStringArray(R.array.stars);
        // 创建新的数组，长度为两个数组的长度之和
        String[] newArray = new String[items.length + Types.length];
        // 将array1的元素复制到newArray,排在前面
        System.arraycopy(items, 0, newArray, 0, items.length);
        // 将array2的元素复制到newArray排在后面
        System.arraycopy(Types, 0, newArray,items.length,Types.length);
        // 使用 LinkedHashSet 过滤重复元素并保留顺序
        LinkedHashSet<String> set = new LinkedHashSet<>(Arrays.asList(newArray));
        // 将去重后的元素存放到新的数组中
        String[] Types2 = set.toArray(new String[0]);
        // 打印去重后的数组元素
        System.out.println(Arrays.toString(Types2));

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.activity_list_drop, Types2!=null?Types2:items);
        //第一个参数表示在哪个Activity上显示，第二个参数是系统下拉框的样式，第三个参数是数组。
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String text = spinner.getItemAtPosition(position).toString();
                if(position==0){
                    Log.e("log",text);
                    getData();
                    count.setText(String.valueOf(note_data.size()) + "条笔记");
                    myadapter.setData(note_data);
                }else {
                    Log.e("log",text);
                        getFenleiData(text);
                        count.setText(String.valueOf(note_data.size()) + "条笔记");
                        myadapter.setData(note_data);

                }

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }


    protected void setItemClick(final List<String> filter_lists) {
        listViewsearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // 点击对应的item时，弹出toast提示所点击的内容
                Log.e("TAG", filter_lists.get(position));
               String itemID=getIdByStr1(note_data,filter_lists.get(position));
                Intent intent = new Intent(getContext(), addNoteFragment.class);
                intent.putExtra("id",itemID);
                startActivity(intent);
            }
        });
    }
    private void setListeners() {
        // 没有进行搜索的时候，也要添加对listView的item单击监听
        setItemClick(lists);

//对编辑框添加文本改变监听，搜索的具体功能在这里实现
//文本该变的时候进行搜索。关键方法是重写的onTextChanged（）方法。
        editTextsearch.addTextChangedListener(new TextWatcher() {

// 编辑框内容改变的时候会执行该方法
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 如果adapter不为空的话就根据编辑框中的内容来过滤数据
                if(myadapter2 != null){
                    myadapter2.getFilter().filter(s);
                    listViewsearch.setVisibility(View.VISIBLE);
                    //叠成置于最前面
                    listViewsearch.bringToFront();
                    M_listViewID.setVisibility(View.GONE);
                }
                String str1 = editTextsearch.getText().toString();
                if(str1.equals("")||str1==null){
                    listViewsearch.setVisibility(View.GONE);
                    M_listViewID.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //根据分类名称查询
    void getFenleiData(String text){
        String[] ziduan = {"bt","neirong","create_time","img","id","fenglei","update_time"};
        Cursor cursor=sqLiteDatabase.query("note_table",ziduan,"fenglei=?",new String[]{text}
                ,null,null,null);
        ArrayList<noteBean> noteBeans = new ArrayList<>();
        //判空
        if (cursor.getCount()>0){
            int value1=cursor.getColumnIndex("neirong");
            int value2=cursor.getColumnIndex("create_time");
            int value3=cursor.getColumnIndex("img");
            int value4=cursor.getColumnIndex("bt");
            int value5=cursor.getColumnIndex("id");
            int value6=cursor.getColumnIndex("fenglei");
            int value7=cursor.getColumnIndex("update_time");
            while (cursor.moveToNext()) {
                String   nr = cursor.getString(value1);
                String   time = cursor.getString(value2);
                String   img = cursor.getString(value3);
                String   bt = cursor.getString(value4);
                String   id=cursor.getString(value5);
                String   fenglei = cursor.getString(value6);
                String   utime = cursor.getString(value7);
                //把日期转为相应的格式
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日 HH:mm");
                String format = dateFormat.format(new Date(time));
               //String format2 = dateFormat.format(new Date(utime));
                noteBean noteBean = new noteBean();
                noteBean.setNeirong(nr);
                noteBean.setBt(bt);
                noteBean.setCreate_time(format);
                noteBean.setImg(img);
                noteBean.setId(id);
                noteBean.setFenglei(fenglei);
                noteBeans.add(noteBean);
            }
            note_data=noteBeans;
        }else {
            note_data=noteBeans;
            Toast.makeText(getActivity(), "筛选获取信息失败", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.add1:
                 ToAdd();
                break;
        }
    }

//跳转
    public void ToAdd(){
        Intent intent = new Intent(getActivity(), addNoteFragment.class);
        startActivity(intent);
    }



}